package com.exp.bookhouse.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exp.bookhouse.pojo.Book;
import com.exp.bookhouse.pojo.Category;
import com.exp.bookhouse.pojo.myUser;
import com.exp.bookhouse.service.BookService;
import com.exp.bookhouse.service.CategoryService;
import com.exp.bookhouse.util.ApiJSONResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Api(value = "书籍管理接口",tags = "管理员管理书籍操作")
@Controller
@RequestMapping("/admin")
public class BookControllerAdmin {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;


    @ApiOperation(value = "查询书籍列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "p", value = "页数", required = false, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "s", value = "显示记录数", required = false, dataType = "Int")
    })
    @GetMapping("/toBook")
    public String toBook(@RequestParam(value = "p", required = false, defaultValue = "1")Integer page,
                         @RequestParam(value = "s", required = false, defaultValue = "5")Integer size,
                         Model model){
        IPage<Book> iPage = bookService.queryBookByPage(page,size);//分页查询书籍列表
        model.addAttribute("iPage",iPage);
        return "book";
    }


    @ApiOperation(value = "查询书籍细节")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "书籍id", required = true, dataType = "Long")
    })
    @GetMapping("/queryBookDetail/{id}")
    public String queryBookDetail(@PathVariable("id")Long id, Model model){
        Book book = bookService.queryBookById(id);
        model.addAttribute("book",book);
        return "bookDetail";
    }

    @GetMapping("/toSaveBook")
    public String toSaveBook(Model model){
        List<Category> categories = categoryService.queryAllCategory();
        model.addAttribute("categories",categories);
        return "bookAdd";
    }


    @ApiOperation(value = "保存书籍信息")
    @PostMapping("/saveBook")
    public @ResponseBody
    ApiJSONResult saveBook(@ApiParam(value = "书籍信息",required = true) @RequestBody Book book) throws Exception {
        bookService.saveBook(book);
        return ApiJSONResult.ok(book);
    }


    @ApiOperation(value = "跳转书籍更新")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "书籍id", required = true, dataType = "Long")
    })
    @GetMapping("/toUpdateBook/{id}")
    public String toUpload(@PathVariable("id")Long id, Model model){
        List<Category> categories = categoryService.queryAllCategory();
        Book book = bookService.queryBookById(id);
        model.addAttribute("categories",categories);
        model.addAttribute("book",book);
        return "bookUpdate";
    }


    @ApiOperation(value = "保存书籍轮播图")
    @PostMapping("/uploadImage")
    public @ResponseBody ApiJSONResult uploadImage(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws IOException {
        if(file == null || file.length <= 0){
            return ApiJSONResult.ok();
        }
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        Map<String, String[]> parameterMap = multipartRequest.getParameterMap();
        String id = parameterMap.get("id")[0];  //书籍id

        bookService.updateBookById(id,file);
        return ApiJSONResult.ok();
    }



    @ApiOperation(value = "删除书籍轮播图")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "书籍id", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "key", value = "轮播图路径", required = true, dataType = "String")
    })
    @PostMapping("/deleteImage")
    public @ResponseBody ApiJSONResult deleteImage(@RequestParam("key")String url, @RequestParam("id")Long id,Model model) throws Exception {
        Book book = bookService.deleteImage(id,url);
        model.addAttribute("book",book);
        return ApiJSONResult.ok();
    }



    @ApiOperation(value = "更新书籍")
    @PostMapping("/updateBook")
    public @ResponseBody ApiJSONResult updateBook(@ApiParam(value = "书籍信息",required = true)@RequestBody Book book){
        System.out.println(book);
        bookService.updateBookById(book);
        return ApiJSONResult.ok(book);
    }


    @ApiOperation(value = "删除书籍")
    @GetMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id")Long id){
        bookService.deleteBook(id);
        return "redirect:/admin/toBook";
    }


    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }



   /* @PostMapping("/uploadTest")
    public @ResponseBody Map<String,Object> uploadTest(@RequestParam("file")MultipartFile[] files, HttpServletRequest request){
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        Map<String, String[]> parameterMap = multipartRequest.getParameterMap();    //获取前端传过来的参数
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        System.out.println("前端传过来的参数：------------");
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();    //key是字符串
            String[] value = entry.getValue();  //value是字符串数组
            System.out.println(key+":"+ Arrays.toString(value));
        }
        System.out.println("文件的个数："+files.length);

        System.out.println("打印文件的名字：--------------");
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }

        //返回前端的json
        Map<String, Object> map = new HashMap<>();
        map.put("status",200);
        map.put("msg","上传成功");
        return map;
    }
*/



//   @RequestMapping("/test")
//   public void testOne(){
//       Subject subject = SecurityUtils.getSubject();
//       myUser myUser = (myUser) subject.getPrincipal();
//       System.out.println(myUser);
//   }



}
